import React, { useState, useEffect, useCallback, memo, useMemo } from 'react';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Switch,
  message,
  Space,
  Popconfirm,
  InputNumber
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import axios from 'axios';

const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:5197';

interface City {
  id: string;
  name: string;
  country: string;
  latitude: number;
  longitude: number;
  timeZone: string;
  isActive: boolean;
}

const CityManagement: React.FC = memo(() => {
  const [cities, setCities] = useState<City[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCity, setEditingCity] = useState<City | null>(null);
  const [form] = Form.useForm();

  // 获取城市列表（使用useCallback优化）
  const fetchCities = useCallback(async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/weather/cities`);
      setCities(response.data);
    } catch (error) {
      message.error('获取城市列表失败');
      console.error('Error fetching cities:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  // 保存城市（新增或编辑，使用useCallback优化）
  const saveCity = useCallback(async (values: any) => {
    try {
      if (editingCity) {
        // 编辑城市
        await axios.put(`${API_BASE_URL}/api/weather/cities/${editingCity.id}`, values);
        message.success('城市更新成功');
      } else {
        // 新增城市
        await axios.post(`${API_BASE_URL}/api/weather/cities`, values);
        message.success('城市添加成功');
      }
      setModalVisible(false);
      setEditingCity(null);
      form.resetFields();
      fetchCities();
    } catch (error) {
      message.error(editingCity ? '城市更新失败' : '城市添加失败');
      console.error('Error saving city:', error);
    }
  }, [editingCity, form, fetchCities]);

  // 删除城市（使用useCallback优化）
  const deleteCity = useCallback(async (cityId: string) => {
    try {
      await axios.delete(`${API_BASE_URL}/api/weather/cities/${cityId}`);
      message.success('城市删除成功');
      fetchCities();
    } catch (error) {
      message.error('城市删除失败');
      console.error('Error deleting city:', error);
    }
  }, [fetchCities]);

  // 切换城市状态（使用useCallback优化）
  const toggleCityStatus = useCallback(async (cityId: string, isActive: boolean) => {
    try {
      await axios.patch(`${API_BASE_URL}/api/weather/cities/${cityId}/status`, { isActive });
      message.success(`城市已${isActive ? '激活' : '停用'}`);
      fetchCities();
    } catch (error) {
      message.error('状态更新失败');
      console.error('Error updating city status:', error);
    }
  }, [fetchCities]);

  // 打开新增/编辑模态框（使用useCallback优化）
  const openModal = useCallback((city?: City) => {
    if (city) {
      setEditingCity(city);
      form.setFieldsValue(city);
    } else {
      setEditingCity(null);
      form.resetFields();
    }
    setModalVisible(true);
  }, [form]);

  // 关闭模态框（使用useCallback优化）
  const closeModal = useCallback(() => {
    setModalVisible(false);
    setEditingCity(null);
    form.resetFields();
  }, [form]);

  // 表格列定义（使用useMemo优化）
  const columns: ColumnsType<City> = useMemo(() => [
    {
      title: '城市名称',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '国家',
      dataIndex: 'country',
      key: 'country',
      width: 100,
    },
    {
      title: '纬度',
      dataIndex: 'latitude',
      key: 'latitude',
      width: 100,
      render: (value: number) => value?.toFixed(4),
    },
    {
      title: '经度',
      dataIndex: 'longitude',
      key: 'longitude',
      width: 100,
      render: (value: number) => value?.toFixed(4),
    },
    {
      title: '时区',
      dataIndex: 'timeZone',
      key: 'timeZone',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 100,
      render: (isActive: boolean, record: City) => (
        <Switch
          checked={isActive}
          onChange={(checked) => toggleCityStatus(record.id, checked)}
          checkedChildren="激活"
          unCheckedChildren="停用"
        />
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (_: any, record: City) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个城市吗？"
            onConfirm={() => deleteCity(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ], [toggleCityStatus, openModal, deleteCity]);

  useEffect(() => {
    fetchCities();
  }, [fetchCities]);

  return (
    <Card
      title="城市管理"
      extra={
        <Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => openModal()}
          >
            添加城市
          </Button>
          <Button
            icon={<ReloadOutlined />}
            onClick={fetchCities}
            loading={loading}
          >
            刷新
          </Button>
        </Space>
      }
    >
      <Table
        dataSource={cities}
        columns={columns}
        rowKey="id"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 个城市`,
        }}
        scroll={{ x: 800 }}
      />

      <Modal
        title={editingCity ? '编辑城市' : '添加城市'}
        open={modalVisible}
        onCancel={closeModal}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={saveCity}
          initialValues={{ isActive: true }}
        >
          <Form.Item
            name="name"
            label="城市名称"
            rules={[
              { required: true, message: '请输入城市名称' },
              { max: 100, message: '城市名称不能超过100个字符' },
            ]}
          >
            <Input placeholder="请输入城市名称" />
          </Form.Item>

          <Form.Item
            name="country"
            label="国家"
            rules={[
              { required: true, message: '请输入国家名称' },
              { max: 100, message: '国家名称不能超过100个字符' },
            ]}
          >
            <Input placeholder="请输入国家名称" />
          </Form.Item>

          <Form.Item
            name="latitude"
            label="纬度"
            rules={[
              { required: true, message: '请输入纬度' },
              { type: 'number', min: -90, max: 90, message: '纬度必须在-90到90之间' },
            ]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入纬度"
              precision={6}
              step={0.000001}
            />
          </Form.Item>

          <Form.Item
            name="longitude"
            label="经度"
            rules={[
              { required: true, message: '请输入经度' },
              { type: 'number', min: -180, max: 180, message: '经度必须在-180到180之间' },
            ]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入经度"
              precision={6}
              step={0.000001}
            />
          </Form.Item>

          <Form.Item
            name="timeZone"
            label="时区"
            rules={[
              { required: true, message: '请输入时区' },
              { max: 50, message: '时区不能超过50个字符' },
            ]}
          >
            <Input placeholder="例如: Asia/Shanghai" />
          </Form.Item>

          <Form.Item
            name="isActive"
            label="状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="激活" unCheckedChildren="停用" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={closeModal}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingCity ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
});

CityManagement.displayName = 'CityManagement';

export default CityManagement;